//
// Created by 周圳元 on 2023/3/30.
//
#include "../../include/group_db.h"
#include <stdbool.h>
#define SQL_MAX 200
#define error(stats,errormsg) do { 						\
	     if (stats != SQLITE_OK) {                      \
              printf("%s\n",errormsg);                  \
              return -1;                                \
         }                                   	        \
	} while(0);
#define GROUP_TS (*(group_result))



int callback(void *data, int argc, char **argv, char **col_names) {
    group_t **group_result = (group_t **) data;
    group_t **test = group_result;
    GROUP_TS->group_id = atoi(argv[0]);
    strcpy(GROUP_TS->group_name, argv[1]);
    GROUP_TS->creator_id = atoi(argv[2]);
    strcpy(GROUP_TS->creator_name, argv[3]);
    GROUP_TS->create_time = atoi(argv[4]);
    strcpy(GROUP_TS->remark, argv[5]);
    (*test)++;
    return 0;
}



sqlite3* open_group() {
    sqlite3 *db;
    int rc = sqlite3_open(DATABASE_PATH, &db);
    if (rc) {
        fprintf(stderr,"Can't open database: %s",sqlite3_errmsg(db));
        sqlite3_close(db);
        return NULL;
    }
    return db;
}
/**
 *
 * @param midden
 * @param key
 * @param value
 * @return
 */
int key_value_string(char *sql,char *midden,char *key,char* value,char *ret) {
    return sprintf(ret,"%s %s %s='%s'",sql,midden,key,value);
}
/**
 *
 * @param midden
 * @param key
 * @param value
 * @return
 */
int key_value_int(char *sql,char *midden,char *key,int value,char *ret) {
    return sprintf(ret,"%s %s %s=%d",sql,midden,key,value);
}

void sql_format(char *sql,group_t group) {
    printf("断点12 \n");
    int where_flag = 1;
    char *where = "where";
    char *and = "and";
    printf("断点13 \n");
    if (group.remark[0] != '\0') {
        key_value_string(sql,where,"remark",group.remark,sql);
        where_flag = 0;
    }
    printf("断点14 \n");
    if (group.creator_id != 0) {
        printf("断点15 \n");
        if (where_flag) {
            // 此时如果启动就需要where
            key_value_int(sql,where,"creator_id",group.creator_id,sql);
            where_flag = 0;
            printf("断点16 \n");
        } else {
            printf("断点17 \n");
            //否则说明已经有where，则拼接and
            key_value_int(sql,and,"creator_id",group.creator_id,sql);
        }
        printf("断点18 \n");
    }
//    printf("断点15 \n");
    if (group.group_id != 0) {
        if (where_flag) {
            // 此时如果启动就需要where
            key_value_int(sql,where,"group_id",group.group_id,sql);
            where_flag = 0;
        } else {
            key_value_int(sql,and,"group_id",group.group_id,sql);
            //否则说明已经有where，则拼接and
        }
    }
    sprintf(sql,"%s;",sql);
//    printf(sql);
}

group_t* select_group(group_t group,int *len,int flag) {
    printf("断点 5 %d \n",group.creator_id);
    group_t *group_result = (group_t *)(malloc(sizeof(group_t)*100));
    group_t *group_result2 = group_result;
    char *errormsg = NULL;
    char sql[SQL_MAX] = "select * from t_group";
    sql_format(sql,group);
    printf("%s,%s \n",errormsg,sql);
    if (flag) {
        sprintf(sql,"%s %s",sql,"order by group_id desc");
    }
    int exec =  sqlite3_exec(open_group(),sql,callback,(void *)&group_result,&errormsg);
    error(exec,errormsg);
    // 数组的长度
    *len = group_result - group_result2;
    return group_result2;
}

/**
 * 执行sql
 * @param sql
 * @return 失败返回 -1 成功返回 0
 */
int sql_insert_run(char *sql) {
    char *errormsg = NULL;
    int exec =  sqlite3_exec(open_group(),sql,NULL,NULL,&errormsg);
    error(exec,errormsg);
    return 0;
}

int insert_group(group_t group) {
    char sql[SQL_MAX];
//    printf("执行sql");
    sprintf(sql,"INSERT INTO \"main\".\"t_group"
                "\"(\"group_name\", \"creator_id\", \"creator_name\", \"create_time\", \"remark\")"
                " VALUES ('%s', %d, '%s', '%d', '%s');",
                group.group_name,group.creator_id,group.creator_name,group.create_time,group.remark);
    return sql_insert_run(sql);
//    return 0;
}

int update_group(group_t group) {
    char sql[SQL_MAX];
    sprintf(sql,"UPDATE \"main\".\"t_group\" "
                "SET \"group_name\" = '%s', \"creator_id\" = %d, \"creator_name\" = '%s', \"create_time\" = '%d', \"remark\" = '%s' "
                "WHERE \"group_id\" = %d;",
            group.group_name,group.creator_id,group.creator_name,group.create_time,group.remark,group.group_id);
    return sql_insert_run(sql);
}

int delete_group(int groupId) {
    char sql[SQL_MAX];
    sprintf(sql, "DELETE FROM t_group where group_id = %d", groupId);
    return sql_insert_run(sql);
}


int get_join_groups(int user_id,group_t *group)
{

    //制作句柄
    sqlite3 *ppDb;
    sqlite3_stmt *ppStmt;

    //打开操作
    int ret=sqlite3_open(DATABASE_PATH,&ppDb);
    if(ret!=SQLITE_OK){
            perror("sqlite_open error");
            return -1;
    }

    printf("已打开数据库\n");

    //查询用户信息
    char sql[100] = "select g.group_id,g.group_name from t_group g left join t_group_member gm on g.group_id = gm.group_id where group_member_id = ?;";
    ret = sqlite3_prepare_v2(ppDb,sql,-1,&ppStmt,NULL);
    if(ret != SQLITE_OK) {
        perror("sqlite_prepare");
        return -1;
    }

    sqlite3_bind_int(ppStmt, 1,user_id);

    bool flag = false;
    int count = 0;
    while(sqlite3_step(ppStmt) == SQLITE_ROW) {
	group_t g;
        g.group_id = sqlite3_column_int(ppStmt,0);
        strcpy(g.group_name,sqlite3_column_text(ppStmt,1));

        flag = true;
        group[count++] = g;
    }

    if(!flag) {
        sqlite3_finalize(ppStmt);
        sqlite3_close(ppDb);
        return -1;
    }

    sqlite3_finalize(ppStmt);
    sqlite3_close(ppDb);
    return count;
}
